package com.cms.exception;

/**
 * @description : 
 * @author : songfayuan
 * @create : 2020年10月21日
 **/
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常处理
 * 只有代码出错或者throw出来的异常才会被捕捉处理，如果被catch的异常，就不会被捕捉，除非catch之后再throw异常。
 *
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
	
    /**
     * 400 - 错误的请求
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ModelAndView handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("错误的请求", e);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error/400");
        return mv;
    }
    
    
    /**
     * 404 -没有找到
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public ModelAndView handleNotFoundException(NoHandlerFoundException e) {
        log.error("资源没有找到", e);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error/404");
        return mv;
    }
    
    /**
     * 405 - 方法不允许
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ModelAndView handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("没有权限！", e);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error/405");
        return mv;
    }
    
    /**
     * 415 - 不支持的媒体类型
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public ModelAndView handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        log.error("不支持的媒体类型", e);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error/415");
        return mv;
    }
    
    /**
     * 500 - 内部服务器错误
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ModelAndView handleUnauthorizedException(Exception e) {
        log.error("内部服务器错误", e);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error/500");
        return mv;
    }
}
